package org.phoenixframework.api.rbac.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.phoenixframework.api.rbac.mapper.SysAuthorityMapper;
import org.phoenixframework.api.rbac.mapper.SysUserMapper;
import org.phoenixframework.api.rbac.service.ISysAuthorityService;
import org.phoenixframework.api.rbac.util.AuthorityUtil;
import org.phoenixframework.common.entity.SysAuthority;
import org.phoenixframework.common.entity.SysUser;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统权限表 服务实现类
 * </p>
 *
 * @author doublelife
 * @since 2021-05-08
 */
@AllArgsConstructor
@Service
public class SysAuthorityServiceImpl extends ServiceImpl<SysAuthorityMapper, SysAuthority> implements ISysAuthorityService {

    private final SysAuthorityMapper sysAuthorityMapper;

    private final SysUserMapper sysUserMapper;

    @Override
    public List<String> findAuthorityValueByUserId(Long sysUserId) {
        SysUser sysUser = sysUserMapper.selectById(sysUserId);
        if (sysUser.getIsSuper() == 1) {
            LambdaQueryWrapper<SysAuthority> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysAuthority::getType, "2");
            return sysAuthorityMapper.selectList(wrapper).stream().map(SysAuthority::getAuthorityValue).collect(Collectors.toList());
        } else {
            return sysAuthorityMapper.findAuthorityValueByUserId(sysUserId);
        }
    }

    @Override
    public List<JSONObject> listAuthorities(Long sysUserId) {

        SysUser sysUser = sysUserMapper.selectById(sysUserId);
        List<SysAuthority> sysAuthorities;
        if (sysUser.getIsSuper() == 1) {
            sysAuthorities = baseMapper.selectList(null);
        } else {
            sysAuthorities = baseMapper.listBySysUserId(sysUserId);
        }
        List<SysAuthority> treeNodes = AuthorityUtil.build(sysAuthorities);
        return AuthorityUtil.buildByVue(treeNodes);
    }

    @Override
    public Map<String, Object> findAuthoritiesByRoleId(Long roleId) {
        // 所有的权限
        List<SysAuthority> sysAuthorities = this.baseMapper.selectList(null);
        // 根据角色Id查询已经分配的权限
        List<SysAuthority> authoritiesByRoleId = this.baseMapper.findAuthoritiesByRoleId(roleId);

        List<SysAuthority> authorities = sysAuthorities.stream().peek(item -> {
            if (authoritiesByRoleId.contains(item)) {
                item.setSelect(Boolean.TRUE);
            }
        }).collect(Collectors.toList());

        List<Long> checked = authorities.stream()
                .filter(item -> "2".equals(item.getType()))
                .filter(item -> Boolean.TRUE.equals(item.isSelect()))
                .map(SysAuthority::getId)
                .collect(Collectors.toList());

        HashMap<String, Object> result = new HashMap<>(8);
        result.put("items", AuthorityUtil.build(authorities));
        result.put("checked", checked);
        return result;
    }

    private void findChildrenIdByParentId(Long parentId, List<Long> ids) {
        LambdaQueryWrapper<SysAuthority> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysAuthority::getParentId, parentId);
        List<SysAuthority> sysAuthorities = this.baseMapper.selectList(wrapper);
        sysAuthorities.forEach(item -> {
            ids.add(item.getId());
            this.findChildrenIdByParentId(item.getId(), ids);
        });

    }

    @Override
    public boolean removeChildrenById(Long id) {
        ArrayList<Long> ids = new ArrayList<>();
        ids.add(id);
        this.findChildrenIdByParentId(id, ids);
        return this.baseMapper.deleteBatchIds(ids) > 0 ? Boolean.TRUE : Boolean.FALSE;
    }
}
